package com.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import util.CardPlay;
import modle.Card;
import modle.CardGame;
import modle.CardGames;
import modle.User;
import util.JsonChange;

/**
 * Servlet implementation class RobotPlayingServlet
 */
@WebServlet("/RobotPlayingServlet")
/**
 * 接收前端人机信息，并返回其出牌信息
 * @author WXE
 *
 */
public class RobotPlayingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RobotPlayingServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    @Override 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String judgement = request.getParameter("Judgement");
		List<Card> re = null;
		System.out.println("judgement:"+judgement);
		
		User user = (User) request.getSession().getAttribute("user");
		CardGames cardGames = (CardGames) this.getServletContext().getAttribute("CardGames");
		
		System.out.println(user.toString());
		int cardGameID = user.getCardGameID();
		Map<Integer, CardGame> games = cardGames.getCardGames();
		CardGame cardGame = games.get(cardGameID);
		String robot2 = "2";
		String robot0 = "0";
		//2号人机出牌
		if(robot2.equals(judgement)) {
			re = JsonChange.toCard(CardPlay.comptuerShowCards(2, cardGame));
			if( re.isEmpty() ) {
				cardGame.getFlag()[2] = false;
				cardGame.getCurrentList()[2] = re;
			}else {
				cardGame.getFlag()[2] = true;
				cardGame.getCurrentList()[2] = re;
			}
		}
		//0号人机出牌
		else if(robot0.equals(judgement)) {
			re = JsonChange.toCard(CardPlay.comptuerShowCards(0, cardGame));
			if( re.isEmpty() ) {
				cardGame.getFlag()[0] = false;
				cardGame.getCurrentList()[0] = re;
			}else {
				cardGame.getFlag()[0] = true;
				cardGame.getCurrentList()[0] = re;
			}
		}
		response.getWriter().println(JSON.toJSONString(re));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
    @Override 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}